package com.base.sms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.ConfigConstants;
import com.base.common.enums.AppType;
import com.base.common.enums.SmsCategories;
import com.base.common.enums.SmsReportStatus;
import com.base.common.enums.SmsType;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.EmployeeCompoundsMapper;
import com.base.common.persistent.dao.EmployeeMapper;
import com.base.common.persistent.dao.SmsMapper;
import com.base.common.persistent.dao.SmsReportMapper;
import com.base.common.persistent.dao.TerminalMapper;
import com.base.common.persistent.model.Employee;
import com.base.common.persistent.model.Sms;
import com.base.common.persistent.model.SmsReport;
import com.base.common.persistent.model.Terminal;
import com.base.common.utils.EasyUtil;
import com.base.common.utils.IDGenerator;
import com.base.common.utils.PushUtils;
import com.base.sms.service.SmsService;
import com.opensymphony.xwork2.ActionContext;

@Service("smsService")
public class SmsServiceImpl implements SmsService {

	@Resource
	private SmsMapper smsMapper;

	@Resource
	private SmsReportMapper smsReportMapper;

	@Resource
	private EmployeeMapper employeeMapper;

	@Resource
	private EmployeeCompoundsMapper employeeCompoundsMapper;

	@Resource
	private TerminalMapper terminalMapper;

	@Resource
	private EasyUtil easyUtil;

	@Override
	public List<Sms> getSmsByFuzzyCondition(int bid, int categories,
			String code, int status, int page) {
		String uuid = null;
		List<Sms> smss = new ArrayList<Sms>();
		Terminal terminal = terminalMapper.queryRegistedTerminalByCodeAndBid(
				code, bid);
		smss = smsMapper.querySmsByFuzzyCondition(uuid, categories,
				terminal.getId(), SmsType.MAIN.getValue(), (page - 1) * 15,
				Integer.parseInt(ConfigConstants.INFOS_LIST_NUM), status);
		return smss;
	}

	@Override
	public int getSmsCountsByFuzzyCondition(int bid, int categories,
			String code, int status) {
		String uuid = null;
		Terminal terminal = terminalMapper.queryRegistedTerminalByCodeAndBid(
				code, bid);
		return smsMapper.querySmsCountsByFuzzyCondition(uuid, categories,
				terminal.getId(), SmsType.MAIN.getValue(), status);
	}

	@Override
	@Transactional
	public int updateReadTimeStatusByReportId(String[] reportIds) {
		try {
			for (String reportId : reportIds) {
				smsReportMapper.updateReadTimeStatusById(new Date(),
						SmsReportStatus.READ.getValue(),
						Integer.valueOf(reportId.trim()));
			}

		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	@Override
	@Transactional
	public int deleteSms(String smsReportIds) {
		try {
			for (String param : smsReportIds.split(",")) {
				String[] params = param.split("-");
				if (params.length == 1) {
					smsReportMapper.updateVisiblenessById(1, -1,
							Integer.valueOf(params[0].trim()));
				} else {
					if (Integer.valueOf(params[1].trim()) == 0) {
						smsReportMapper.updateVisiblenessById(1, -1,
								Integer.valueOf(params[0].trim()));
					}
					if (Integer.valueOf(params[1].trim()) == 1) {
						smsReportMapper.updateVisiblenessById(-1, 1,
								Integer.valueOf(params[0].trim()));
					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	// @Transactional
	@Override
	public int sendSmsToOther(List<Integer> employeeIds, String mess)
			throws Exception {
		// 获取session, 查找员工信息
		Map<String, Object> session = ActionContext.getContext().getSession();
		List<Employee> employees = (List<Employee>) session.get("users");

		for (int employeeId : employeeIds) {
			Employee employee = employeeMapper.queryEmployeeById(employeeId);
			String smsUuid = IDGenerator.getUUID().replace("-", "");

			// 添加主消息
			addSms(SmsCategories.PERSONMESS.getValue(),
					SmsCategories.PERSONMESS.getName(), "",
					employee.getPhone(), SmsType.MAIN.getValue(), smsUuid, 0,
					employee.getTerminal().getId(), employees.get(0)
							.getTerminal().getId());
			List<Sms> smss = smsMapper.querySmsByUuid(smsUuid);
			Sms sms = addSms(SmsCategories.PERSONMESS.getValue(),
					SmsCategories.PERSONMESS.getName(), mess,
					employee.getPhone(), SmsType.CHILD.getValue(), IDGenerator
							.getUUID().replace("-", ""), smss.get(0).getId(),
					employee.getTerminal().getId(), employees.get(0)
							.getTerminal().getId());

			// 判断员工的设备是ios还是android
			String clientId = null;
			if (employee.getTerminal() != null) {
				if (employee.getTerminal().getAndroidClientId() != null
						&& employee.getTerminal().getAndroidClientId().trim() != "") {
					clientId = employee.getTerminal().getAndroidClientId();
				} else if (employee.getTerminal().getAppleClientId() != null
						&& employee.getTerminal().getAppleClientId().trim() != "") {
					clientId = employee.getTerminal().getAppleClientId();
				}

				// 推送通知
				sms.setTitle("来自" + employees.get(0).getName() + "的消息");
				System.out.println(PushUtils.pushtoSingle(clientId,
						JsonUtil.dto2String(sms), AppType.YGJ.getValue()));
			} else {
				throw new Exception();
			}

			// int employeeCompoundsId =
			// employeeCompoundsMapper.queryEmployeeCompoundsIdByEmployeeIdAndCompoundsId(employeeId,
			// compoundsId);
			/*
			 * Sms sms = new Sms();
			 * sms.setCategories(SmsCategories.PERSONMESS.getValue());
			 * sms.setContext(mess); SmsReport smsReport = new SmsReport();
			 * smsReport.setEmployeeCompoundsId(employeeCompoundsId);
			 * smsReport.setSms(sms);
			 */
		}
		return 1;
	}

	/**
	 * 添加短消息
	 * 
	 * @param categories
	 *            消息类别
	 * @param title
	 *            消息标题
	 * @param context
	 *            消息内容
	 * @param resourceEmployeeId
	 *            消息发送者的员工id
	 * @param sendPhone
	 *            消息接收号码
	 * @param employeeId
	 *            消息接收员工小区中间表id
	 * @param userId
	 *            消息接收业主id
	 */
	public Sms addSms(int categories, String title, String context,
			String receivePhone, int type, String smsUuid, int smsId,
			int reveiveTerminalId, int senderTerminalId) {
		Sms sms = new Sms();
		sms.setCategories(categories);
		sms.setType(type);
		sms.setTitle(title);
		sms.setCreateTime(new Date());
		// String uuid = IDGenerator.getUUID().replace("-", "");
		sms.setUuid(smsUuid.trim());
		sms.setContext(context);
		sms.setSmsId(smsId);
		smsMapper.addSms(sms);

		SmsReport smsReport = new SmsReport();
		smsReport.setSendTime(new Date());
		smsReport.setStatus(SmsReportStatus.NOTREAD.getValue());
		smsReport.setSms(smsMapper.querySmsByUuid(smsUuid.trim()).get(0));
		smsReport.setReceivePhone(receivePhone);
		smsReport.setReceiveVisibleness(0);
		smsReport.setSenderVisibleness(0);
		smsReport.setReceiveTerminalId(reveiveTerminalId);
		smsReport.setSenderTerminalId(senderTerminalId);
		smsReportMapper.addSmsReport(smsReport);
		return sms;
	}

	@Override
	public int replySms(List<Integer> employeeIds, int smsId, String mess)
			throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
		List<Employee> employees = (List<Employee>) session.get("users");

		for (int employeeId : employeeIds) {
			Employee employee = employeeMapper.queryEmployeeById(employeeId);

			// 添加主消息
			Sms sms = addSms(SmsCategories.PERSONMESS.getValue(),
					SmsCategories.PERSONMESS.getName(), mess,
					employee.getPhone(), SmsType.CHILD.getValue(), IDGenerator
							.getUUID().replace("-", ""), smsId, employee
							.getTerminal().getId(), employees.get(0)
							.getTerminal().getId());

			// 判断员工的设备是ios还是android
			String clientId = null;
			if (employee.getTerminal() != null) {
				if (employee.getTerminal().getAndroidClientId() != null
						&& employee.getTerminal().getAndroidClientId().trim() != "") {
					clientId = employee.getTerminal().getAndroidClientId();
				} else if (employee.getTerminal().getAppleClientId() != null
						&& employee.getTerminal().getAppleClientId().trim() != "") {
					clientId = employee.getTerminal().getAppleClientId();
				}

				// 推送通知
				sms.setTitle("来自" + employees.get(0).getName() + "的消息");
				System.out.println(PushUtils.pushtoSingle(clientId,
						JsonUtil.dto2String(sms), AppType.YGJ.getValue()));
			} else {
				throw new Exception();
			}

		}
		return 1;
	}

	/*
	 * @Test public void test() throws Exception { List<Integer> intergers = new
	 * ArrayList<Integer>(); intergers.add(3); intergers.add(4);
	 * System.out.println(JsonUtil.dto2String(intergers)); }
	 */

}
